import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutterclue/mvp/mode/MessageListBean.dart';
import 'package:flutterclue/r.dart';
import 'package:flutterclue/utils/ToastUtilForAndroid.dart';
import 'package:flutterclue/view/progreess_dialog.dart';
import 'package:flutterclue/mvp/presenter/MessagePagePrensenter.dart';
import 'package:flutterclue/view/EndLine.dart';
import 'ClueDetailPage.dart';

class MessagePage extends StatefulWidget {
  @override
  _MessagePageState createState() => new _MessagePageState();
}

class _MessagePageState extends State<MessagePage> implements MessagePageView {
  final GlobalKey<RefreshIndicatorState> _refreshIndecatorKey = new GlobalKey();
  final _presenter = new MessagePagePresenter();
  ScrollController _scrollController;

  ///抢单列表
  List<RobbingBean> _qDDataList = new List();

  ///消息列表
  List<MessageBean> _dataList = new List();
  Map _messageTypeMap = {
    "0": "出险通知",
    "1": "超时通知",
    "2": "回访通知",
    "3": "接车通知",
    "4": "流失通知",
    "5": "到店通知",
    "6": "接待通知",
    "8": "领取成功",
    "9": "领取失败",
    "10": "定损提醒",
    "11": "已定损",
    "12": "交车提醒",
    "13": "已交车",
    "14": "指派通知",
    "15": "线索过期"
  };

  int _pageIndex = 1;
  bool _isSliedeUo = true;

  ///是否显示加载更多。。
  bool _isShowLoading = false;

  void _scrollListener() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      _isShowLoading = true;
      setState(() {});
      _loadData();
    }
  }

  Future<Null> _loadData() async {
    _isSliedeUo = false;
    _pageIndex = _pageIndex + 1;
    await _presenter.getMessageList(pageIndex: _pageIndex);
    setState(() {});
  }

  Future<Null> _refreshData() async {
    _isSliedeUo = true;
    _pageIndex = 1;
    await _presenter.getMessageList(pageIndex: _pageIndex);
    setState(() {});
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _presenter.attachView(this);
    _scrollController = new ScrollController()..addListener(_scrollListener);
    _refreshData();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();

    _scrollController.removeListener(_scrollListener);
  }

  @override
  Widget build(BuildContext context) {
    var content;
    if (_dataList.isEmpty) {
      content = getProgressDialog();
    } else {
      content = ListView.builder(
          itemCount: _dataList.length + 1 + _qDDataList.length,
          controller: _scrollController,
          physics: AlwaysScrollableScrollPhysics(),
          itemBuilder: buildItem);
    }
    var _refreshIndecator = new RefreshIndicator(
      child: content,
      onRefresh: _refreshData,
      key: _refreshIndecatorKey,
    );
    return _refreshIndecator;
  }

  Widget buildItem(BuildContext context, int index) {
    if (_qDDataList.length <= 0) {
      return buildMsgItem(context, index);
    } else {
      if (index < _qDDataList.length) {
        return new Text(_qDDataList[index].LicenseNo);
      } else {
        return buildMsgItem(context, index - _qDDataList.length);
      }
    }
  }

  Widget buildMsgItem(BuildContext context, int index) {
    if (index == _dataList.length) {
      if (_isShowLoading) {
        return new LoadMoreView();
      } else {
        return new EndLine();
      }
    } else {
      return new Material(
        child: InkWell(
          onTap: () {
            Navigator.of(context).push(new PageRouteBuilder(
                opaque: false,
                pageBuilder: (BuildContext context, _, __) {
                  return new ClueDetailPage(clueId: _dataList[index].CuleId);
                },
                transitionsBuilder:
                    (_, Animation<double> animation, __, Widget child) {
                  return new SlideTransition(
                    //相当于android中的估值器
                    position: new Tween<Offset>(
                      begin: const Offset(1.0, 0.0),
                      end: const Offset(0.0, 0.0),
                      //相当于android中的差值器
                    ).animate(new CurvedAnimation(
                        parent: animation, curve: Curves.easeOut)),
                    child: child,
                  );
                }));
          },
          child: Container(
            child: Column(
              children: <Widget>[
                new ListTile(
                  leading: new Image.asset(
                    R.imagesIcMessageDangerPng,
                    width: 44,
                    height: 44,
                  ),
                  subtitle: Padding(
                    padding: const EdgeInsets.only(top: 5),
                    child: new Text(
                      _dataList[index].Content,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  trailing: Padding(
                    padding: EdgeInsets.only(bottom: 22),
                    child: new Text(_getDateFormat(_dataList[index].CreateTime,
                        _dataList[index].TimeDifference)),
                  ),
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      new Text(_messageTypeMap[
                                  "${_dataList[index].MesaageType}"] ==
                              null
                          ? ""
                          : "${_messageTypeMap["${_dataList[index].MesaageType}"]}"),
                      Offstage(
                        offstage: _dataList[index].MesaageType == 1 &&
                                _dataList[index].TimeoutNoticeCount > 1
                            ? false
                            : true,
                        child: new Container(
                          margin: EdgeInsets.only(left: 4, right: 4),
                          height: 17,
                          width: 17,
                          decoration: new BoxDecoration(
                              color: _dataList[index].IsHandle == 0
                                  ? Color(0xffFF4444)
                                  :Color(0xffcccccc) ,
                              shape: BoxShape.circle),
                          child: Center(
                            child: new Text(
                              '${_dataList[index].TimeoutNoticeCount}',
                              style:
                                  TextStyle(fontSize: 10, color: Colors.white),
                            ),
                          ),
                        ),
                      ),
                      Offstage(
                        offstage: _dataList[index].IsHandle == 0 ? true : false,
                        child: new Container(
                          margin: EdgeInsets.only(left: 4, right: 4),
                          height: 18,
                          width: 44,
                          decoration: new BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(2.0)),
                              color: Colors.white,
                              border: Border.all(
                                  color: Theme.of(context).accentColor)),
                          child: Center(
                            child: new Text(
                              '已处理',
                              style: TextStyle(
                                  fontSize: 9,
                                  color: Theme.of(context).accentColor),
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                new Divider()
              ],
            ),
          ),
        ),
      );
    }
  }

  @override
  dismissLoadingView() {}

  @override
  void onFail(String message) {
    ToastUtil.showShort(message);
  }

  @override
  void onSuccessMessageListBean(MessageListBean messageListBean) {
    if (!mounted) return;
    if (_isSliedeUo) {
      _dataList.clear();
    } else {
      if (messageListBean.MessageList.isEmpty) {
        _isShowLoading = false;
      } else {
        _isShowLoading = true;
      }
    }
    _dataList.addAll(messageListBean.MessageList);
    setState(() {});
  }

  @override
  showLoadingView() {}
}

String _getDateFormat(String createTime, double timeDifference) {
  double mMessageTime = timeDifference / 60 + 0.5;
  if (mMessageTime.toInt() < 60) {
    if (mMessageTime.toInt() == 0) {
      return "现在";
    } else {
      return "${mMessageTime.toInt()}分钟前";
    }
  } else if (mMessageTime.toInt() < 1439 && mMessageTime.toInt() >= 60) {
    return "${(mMessageTime.toInt() / 60.0 + 0.5).toInt()}小时前";
  } else {
    return createTime.substring(0, 10);
  }
}
